package rxhttpext.parser

import okhttp3.Response
import rxhttp.RxHttpPlugins
import rxhttp.wrapper.OkHttpCompat
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.exception.ExceptionHelper
import rxhttp.wrapper.parse.AbstractParser
import rxhttpext.ApiException
import rxhttpext.Converter
import java.io.IOException
import java.lang.reflect.Type

/**
 * 用在某些不同code，data数据结构会不同的奇葩接口上
 * 只有code==1的时候，才会去反序列化json数据，否则直接抛出异常
 */
@Parser(name = "Bean01")
open class Bean01Parser<T> : AbstractParser<T> {

    protected constructor() : super()

    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: Response): T {

        val body = ExceptionHelper.throwIfFatal(response)
        body.use {
            val needDecodeResult = OkHttpCompat.needDecodeResult(response)

            var result = it.string()
            if (needDecodeResult) {
                result = RxHttpPlugins.onResultDecoder(result)
            }

            val jsonElement = Converter.toJsonElement(result)
            val jsonObject = jsonElement.asJsonObject
            val code = jsonObject["code"].asInt
            val msg = jsonObject["msg"].asString
            if (code == 1) {
                return Converter.toBean(jsonElement, mType)
            } else {
                throw ApiException(msg ?: code.toString(), code)
            }
        }
    }
}